package main

import (
	"fmt"
)

type Node struct {
	Value       int
	Left, Right *Node
}

func (node Node) Print() {
	fmt.Print(node.Value, " ")
}

func (node *Node) Traverse() {
	node.TraverseFunc(func(n *Node) {
		n.Print()
	})
	fmt.Println()
}

func (node *Node) TraverseFunc(f func(*Node)) {
	if node == nil {
		return
	}
	node.Left.TraverseFunc(f)
	//传入需要操作的函数
	f(node)
	node.Right.TraverseFunc(f)
}

func (node *Node) TraverseWithChannel() chan *Node {
	out := make(chan *Node)
	go func() {
		node.TraverseFunc(func(node *Node) {
			out <- node
		})
		close(out)
	}()
	return out
}

func main() {
	testMyTreeNode()
}

func testMyTreeNode() {
	fmt.Println("-------- testMyTreeNode --------")
	//中序遍历 0 2 3 4 5
	var root Node
	//初始化一个值
	root = Node{Value: 3}
	//默认值初始化
	root.Left = &Node{}
	root.Left.Right = &Node{2, nil, nil}
	//不指定字段初始化需要给所有字段赋值
	root.Right = &Node{5, nil, nil}
	//注意: 指针类型(*)在go中也可以用 . 来获取其值
	root.Right.Left = &Node{4, nil, nil}

	root.Traverse()
	fmt.Println()
	nodeCnt := 0
	root.TraverseFunc(
		func(node *Node) {
			nodeCnt++
		},
	)
	fmt.Println("nodeCnt=", nodeCnt)
	fmt.Println()
}
